//
//  ConversationSearchTableViewController.m
//  WFChat UIKit
//
//  Created by WF Chat on 2017/8/29.
//  Copyright © 2017年 WildFireChat. All rights reserved.
//

#import "WFCUConversationSearchTableViewController.h"
#import "WFCUContactListViewController.h"
#import "WFCUFriendRequestViewController.h"

#import "WFCUMessageListViewController.h"

#import <SDWebImage/SDWebImage.h>
#import "WFCUUtilities.h"
#import "UITabBar+badge.h"
#import "KxMenu.h"
#import "UIImage+ERCategory.h"
#import "MBProgressHUD.h"

#import "WFCUConversationSearchTableViewCell.h"
#import "WFCUConfigManager.h"
#import "WFCUImage.h"
#import "SDAutoLayout.h"


#import "MWPhotoBrowser.h"
#import "YGExtendChain.h"

#import "FSCalendar.h"

@interface WFCUConversationSearchTableViewController () <UISearchControllerDelegate, UISearchResultsUpdating, UITableViewDelegate, UITableViewDataSource,MWPhotoBrowserDelegate,UICollectionViewDataSource, UICollectionViewDelegate,FSCalendarDataSource,FSCalendarDelegate>

@property (weak, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) NSCalendar *gregorian;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong)NSMutableArray<WFCCMessage* > *messages,*imageMsgs;
@property (nonatomic, strong)  UISearchController       *searchController;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *searchViewContainer;
 
@end



@implementation WFCUConversationSearchTableViewController
- (void)initSearchUIAndTableView {
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    
    if (@available(iOS 9.1, *)) {
        self.searchController.obscuresBackgroundDuringPresentation = NO;
    }
    
    if (@available(iOS 13, *)) {
        self.searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
        self.searchController.searchBar.searchTextField.backgroundColor = [WFCUConfigManager globalManager].naviBackgroudColor;
//        UIImage* searchBarBg = [UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(self.view.frame.size.width - 8 * 2, 36) cornerRadius:4];
        
//        [self.searchController.searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
        [self.searchController.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bag1"] forState:UIControlStateNormal];

    } else {
        [self.searchController.searchBar setValue:WFCString(@"Cancel") forKey:@"_cancelButtonText"];
    }
    
    self.searchController.searchBar.placeholder = WFCString(@"Search");
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = _searchController;
        self.navigationItem.hidesSearchBarWhenScrolling = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
    } else {
        self.tableView.tableHeaderView = _searchController.searchBar;
    }
    
    self.definesPresentationContext = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.messages = [[NSMutableArray alloc] init];
    self.imageMsgs = [[NSMutableArray array]init];
    [self initSearchUIAndTableView];
   
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    [self.searchController.searchBar setText:self.keyword];
    self.searchController.active = YES;
    
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsMake( ZmNavigationHeight_N(), 0, 0, 0));
    self.collectionView.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messages.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WFCUConversationSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[WFCUConversationSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    WFCCMessage *msg = [self.messages objectAtIndex:indexPath.row];
    cell.keyword = self.keyword;
    cell.message = msg;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 68;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 40)];
    UIImageView *portraitView = [[UIImageView alloc] initWithFrame:CGRectMake(4, 4, 32, 32)];
    portraitView.layer.cornerRadius = 3.f;
    portraitView.layer.masksToBounds = YES;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, self.tableView.frame.size.width, 40)];
    
    label.font = [UIFont boldSystemFontOfSize:18];
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentLeft;
//    header.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
    if (self.conversation.type == Single_Type) {
        WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.conversation.target refresh:NO];
        [portraitView sd_setImageWithURL:[NSURL URLWithString:[userInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[WFCUImage imageNamed:@"PersonalChat"]];
        if(userInfo.displayName.length) {
            label.text = [NSString stringWithFormat:@"\"%@\"的聊天记录", userInfo.displayName];
        } else {
            label.text = @"用户聊天记录";
        }
    } else if (self.conversation.type == Group_Type) {
        WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.conversation.target refresh:NO];
        [portraitView sd_setImageWithURL:[NSURL URLWithString:[groupInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[WFCUImage imageNamed:@"GroupChatRound"]];
        
        
        portraitView.sh_chain_extend.hidden(YES);
        
        if (!self.calendar) {
            
            UIButton *btn = [[UIButton alloc]init];
            [header addSubview:btn];
            btn.sd_layout.centerXEqualToView(header).offset(-50).topEqualToView(header).widthIs(100).heightIs(60);
            btn.sh_chain_extend.title(@"日期查询").titleColorBlue().font_size(17);
            [btn addTarget:self action:@selector(chooseDate:) forControlEvents:UIControlEventTouchUpInside];

            UIButton *btn1 = [[UIButton alloc]init];
            [header addSubview:btn1];
            btn1.sd_layout.leftSpaceToView(btn, 0).topEqualToView(header).widthIs(100).heightIs(60);
            btn1.sh_chain_extend.title(@"图片查询").titleColorBlue().font_size(17);
            [btn1 addTarget:self action:@selector(chooseImg:) forControlEvents:UIControlEventTouchUpInside];
            
            UIView *lineV = [[UIView alloc]init];
            
            [header addSubview:lineV];
            lineV.backgroundColor = [UIColor colorWithHexExtendString:@"#D8D8D8"];
            lineV.sd_layout.heightIs(22).widthIs(1).centerXEqualToView(header).centerYEqualToView(header);
            
        }
       
    } else if(self.conversation.type == Channel_Type) {
        WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:NO];
        [portraitView sd_setImageWithURL:[NSURL URLWithString:[channelInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[WFCUImage imageNamed:@"GroupChatRound"]];
        if(channelInfo.name.length) {
            label.text = [NSString stringWithFormat:@"\"%@\"的聊天记录", channelInfo.name];
        } else {
            label.text = @"频道聊天记录";
        }
    } else if(self.conversation.type == SecretChat_Type) {
        NSString *userId = [[WFCCIMService sharedWFCIMService] getSecretChatInfo:self.conversation.target].userId;
        
        WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:userId refresh:NO];
        [portraitView sd_setImageWithURL:[NSURL URLWithString:[userInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[WFCUImage imageNamed:@"PersonalChat"]];
        label.text = [NSString stringWithFormat:@"\"%@\"的聊天记录", userInfo.displayName];
    }
    
    [header addSubview:label];
    [header addSubview:portraitView];
    return header;
}
-(void)chooseImg:(UIButton *)nub{//
    
    
    
    self.imageMsgs = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:@[@(MESSAGE_CONTENT_TYPE_IMAGE) ] from:0 count:100 withUser:nil].mutableCopy;
    [self.imageMsgs addObjectsFromArray:self.imageMsgs];

    if (@available(iOS 11.0, *)) {

        self.navigationItem.hidesSearchBarWhenScrolling = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
        self.navigationItem.searchController = nil;
        
        
    } else {
//        self.tableView.tableHeaderView = _searchController.searchBar;
        self.tableView.tableHeaderView = nil;
    }
    self.definesPresentationContext = YES;

    self.collectionView.hidden = NO;
    [self.collectionView reloadData];
    
}

-(void)chooseDate:(UIButton *)nub{
    //1代表单选日期，2代表多选日期
    
    if (@available(iOS 11.0, *)) {
        
        self.navigationItem.hidesSearchBarWhenScrolling = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
        self.navigationItem.searchController = nil;
        
    } else {
        
        self.tableView.tableHeaderView = nil;
        
    }
    
    self.definesPresentationContext = YES;
    
//    self.gregorian = [NSCalendar currentCalendar];

    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy-MM-dd";
    
    
    
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, ZmNavigationHeight_N(), ZmScreenWidth_N(), ZmScreenHeight_N() - ZmNavigationHeight_N() )];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.backgroundColor = [UIColor whiteColor];
    calendar.appearance.headerMinimumDissolvedAlpha = 0;
    calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase;
    calendar.appearance.todayColor = [UIColor orangeColor];
    calendar.appearance.todaySelectionColor = [UIColor orangeColor];
    
    
    
    calendar.pagingEnabled = NO;
    calendar.allowsMultipleSelection = NO;
    calendar.rowHeight = 60;
    calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    
    calendar.swipeToChooseGesture.enabled = YES;
    calendar.today = nil; // Hide the today circle
    calendar.scope = FSCalendarScopeWeek;
    
    [self.view addSubview:calendar];
    
    self.calendar =  calendar;
    [self.calendar selectDate:[NSDate date] scrollToDate:YES];
    
    
    
}
//}

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    if ([self.gregorian isDateInToday:date]) {
        return @"今";
    }
    return nil;
}
- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    return [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:0 toDate:[NSDate date] options:0];
}
- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date
{
    if ([self.gregorian isDateInToday:date]) {
        return @[[UIColor orangeColor]];
    }
    return @[appearance.eventDefaultColor];
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    NSLog(@"did select date %@",[self.dateFormatter stringFromDate:date]);
    
    
    self.calendar.hidden = YES;
 
//    NSDate *date = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate: date];
//    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSString *todayDate = [dateFormatter stringFromDate:localeDate];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *startOfDay =  [dateFormatter dateFromString:[[self.dateFormatter stringFromDate:date] stringByAppendingString:@" 00:00:00"]];
    NSDate *endOfDay = [dateFormatter dateFromString:[[self.dateFormatter stringFromDate:date] stringByAppendingString:@" 23:59:59"]];
    
//    [self.gregorian setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
//    [self.gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
//    [self.gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:+28800]];
//    
//    // 获取一天的开始时间 (午夜0点)
//    NSDate *startOfDay = [self.gregorian startOfDayForDate:date];
//     
//    // 获取一天的结束时间 (次日午夜0点)
//    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
//    offsetComponents.day = 1;
//    offsetComponents.second = -1; // 减去1秒是为了到达23:59:59，即当天的最后一秒
////    [offsetComponents setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//
//    NSDate *endOfDay = [self.gregorian dateByAddingComponents:offsetComponents toDate:startOfDay options:0];
     
    // 输出结果
    NSLog(@"开始时间: %.0f", [startOfDay timeIntervalSince1970] );
    NSLog(@"结束时间: %.0f", [endOfDay timeIntervalSince1970] );
    
    
//    @param startTime 消息的开始时间，单位为毫秒，如果不需要开始时间请用0。
//    @param endTime 消息的结束时间，单位为毫秒，如果不需要结束时间请用0.。

    
    self.messages = [[WFCCIMService sharedWFCIMService] searchMessage:self.conversation keyword:nil contentTypes:nil startTime:[startOfDay timeIntervalSince1970] * 1000 endTime:[endOfDay timeIntervalSince1970] * 1000 order:YES limit:100 offset:0 withUser:nil].mutableCopy;
       
    
    NSLog(@" messages = %@" , self.messages );
    
    //刷新表格
    [self.tableView reloadData];
    
    
}














- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.conversation.type == Group_Type) {
        return 60;
    }
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
    
    mvc.conversation = self.messages[indexPath.row].conversation;
    mvc.highlightMessageId = self.messages[indexPath.row].messageId;
    mvc.highlightText = self.keyword;
    mvc.multiSelecting = self.messageSelecting;
    mvc.selectedMessageIds = self.selectedMessageIds;
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.searchController.active) {
        [self.searchController.searchBar resignFirstResponder];
    }
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
    _searchController = nil;
}

#pragma mark - UISearchControllerDelegate
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    if (searchString.length) {
        self.messages = [[[WFCCIMService sharedWFCIMService] searchMessage:self.conversation keyword:searchString order:YES limit:100 offset:0 withUser:nil] mutableCopy];
        self.keyword = searchString;
    } else {
        [self.messages removeAllObjects];
    }
    
    //刷新表格
    [self.tableView reloadData];
}



//self.imageMsgs = imageMsgs;

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.imageMsgs.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    WFCCMessage *msg = self.imageMsgs[index];
    if([msg.content isKindOfClass:[WFCCImageMessageContent class]]) {
        WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)msg.content;
        MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:imgCnt.remoteUrl]];
        photo.message = msg;
        return photo;
    } else if([msg.content isKindOfClass:[WFCCVideoMessageContent class]]) {
        WFCCVideoMessageContent *videoCnt = (WFCCVideoMessageContent *)msg.content;
        MWPhoto *photo = [MWPhoto videoWithURL:[NSURL URLWithString:videoCnt.remoteUrl]];
        photo.message = msg;
        return photo;
    }
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    WFCCMessage *msg = self.imageMsgs[index];
    UIImage *image = nil;
    BOOL video = NO;
    if([msg.content isKindOfClass:[WFCCImageMessageContent class]]) {
        WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)msg.content;
        image = imgCnt.thumbnail;
    } else if([msg.content isKindOfClass:[WFCCVideoMessageContent class]]) {
        WFCCVideoMessageContent *videoCnt = (WFCCVideoMessageContent *)msg.content;
        image = videoCnt.thumbnail;
        video = YES;
    }
    MWPhoto *photo = [MWPhoto photoWithImage:image];
    photo.isVideo = video;
    return photo;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    NSLog(@"Did start viewing photo at index %lu", (unsigned long)index);
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    return NO;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    NSLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    // If we subscribe to this method we must dismiss the view controller ourselves
    NSLog(@"Did finish modal presentation");
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - set_and_get
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //自动网格布局
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        
        flowLayout.headerReferenceSize = CGSizeMake(0, 0); // 设置头部的高度为50

        CGFloat edgeInset = 10;
//        int countInLine = 2;
        flowLayout.sectionInset = UIEdgeInsetsMake(edgeInset, edgeInset, edgeInset, edgeInset);
//        CGFloat width = [UIScreen mainScreen].bounds.size.width;
//        width = (width - edgeInset)/countInLine - edgeInset;
//        flowLayout.itemSize = CGSizeMake(width, width + 20);
        flowLayout.minimumLineSpacing = 10;
//        flowLayout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView setBackgroundColor:[WFCUConfigManager globalManager].backgroudColor];
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        

        [_collectionView registerClass:UICollectionReusableView.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];

        
        self.extendedLayoutIncludesOpaqueBars = YES;
        if (@available(iOS 11.0, *)) {
            self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
            if (ZmIsIphoneX_N()) {
                self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }else{
                self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            }
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
            _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        
        
    }
    return _collectionView;
    
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageMsgs.count ;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    UIImageView *portraitView = [[UIImageView alloc] init ];
    portraitView.userInteractionEnabled = YES;
    [cell.contentView addSubview:portraitView];
    portraitView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
    
    
    WFCCMessage *msg = self.imageMsgs[indexPath.item];
    WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)msg.content;
//    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:imgCnt.remoteUrl]];

    [portraitView sd_setImageWithURL:[NSURL URLWithString:imgCnt.remoteUrl]];

    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"---");
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = NO;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.zoomPhotosToFill = NO;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    browser.enableSwipeToDismiss = NO;
    browser.autoPlayOnAppear = NO;
    
    [browser setCurrentPhotoIndex:indexPath.item];
    [self.navigationController pushViewController:browser animated:YES];
    
    
}

#pragma mark - UICollectionViewDelegateFlowLayout
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
 
    return CGSizeMake( ZmScreenWidth_N()/4 - 13 , ZmScreenWidth_N()/4 - 13 );
}
// UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
    header.backgroundColor = [UIColor lightGrayColor]; // 设置头部的背景颜色
    return header;
}



@end
